import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 引入bootstrap框架
import 'bootstrap/dist/css/bootstrap.css'
// 引入 element-plus
import ElementPlus from 'element-plus'
import "element-plus/theme-chalk/index.css"
// 引入axios库
import axios from 'axios'

import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}


/**
 * 配置请求拦截器
 */
axios.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        // console.log("interceptors.request token = "+token)
        if (token) {
            config.headers.token  = `${token}`;
            // console.log("interceptors.request token2 = "+token)
        }
        return config;
    },
    err => Promise.reject(err)
);

// 配置响应拦截器，主要做登录过期的处理，后端在解析token失效时返回401
axios.interceptors.response.use(res => {
    // 登录过期
    if (res.data.code === 201) {
        message.error("Token认证失败");
        router.push('/login');
    }
    return res;
}, err => {
    return Promise.reject(err);
})

/**
 * 全局路由导航守卫
 */
router.beforeEach((to, from, next) => {
    const path = to.path;
    // console.log("path = ", path);
    // 条件成立：表示跳转的目的路径是系统的主页，需要对其进行token认证
    if (path.indexOf("/main") !== -1) {
        // 获取store的token字符串
        const token = store.state.token;
        // console.log("token ==== ", token);

        if (token) {
            next();
        } else {
            next('/login');
            alert("认证失败，请重新登录");
        }
    } else {
        next();
    }
})

app.config.globalProperties.$axios = axios
app.use(store).use(router).use(ElementPlus).mount('#app')
